package com.itlong.cloud.datasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * <desc>
 *     从数据源配置
 * </desc>
 *
 * @createDate 2017/10/24
 */
@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = SipDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "clusterSqlSessionFactory")
public class SipDataSourceConfig {
 
    // 精确到 sipDataSource 目录，以便跟其他数据源隔离
    static final String PACKAGE = "com.itlong.cloud.datasource.dao";
    static final String MAPPER_LOCATION = "classpath:mapper/sip/datasource/*.xml";

    @Value("${" + PlatformConstants.DATASOURCE_SIP_MYSQL_URL + "}")
    private String url;

    @Value("${" + PlatformConstants.DATASOURCE_SIP_MYSQL_USERNAME + "}")
    private String user;

    @Value("${" + PlatformConstants.DATASOURCE_SIP_MYSQL_PASSWORD + "}")
    private String password;

    @Value("com.mysql.jdbc.Driver")
    private String driverClass;

    @Value("${" + PlatformConstants.SIP_MINIDLE + "}")
    private String SIP_MINIDLE;

    @Value("${" + PlatformConstants.SIP_MAXACTIVE + "}")
    private String SIP_MAXACTIVE;

    @Value("${" + PlatformConstants.SIP_MAXWAIT + "}")
    private String SIP_MAXWAIT;

    @Value("${" + PlatformConstants.SIP_TIMEBETWEENEVICTIONRUNSMILLIS + "}")
    private String SIP_TIMEBETWEENEVICTIONRUNSMILLIS;

    @Value("${" + PlatformConstants.SIP_MINEVICTABLEIDLETIMEMILLIS + "}")
    private String SIP_MINEVICTABLEIDLETIMEMILLIS;

    @Value("${" + PlatformConstants.SIP_REMOVEABANDONEDTIMEOUT + "}")
    private String SIP_REMOVEABANDONEDTIMEOUT;


    @Bean(name = "clusterDataSource")
    public DataSource clusterDataSource() {
        try {
            user = DesEncryptUtil.aesDecrypt(user, url.substring(0, 16));
            password = DesEncryptUtil.aesDecrypt(password, url.substring(0, 16));
            if (StringUtils.isEmpty(user) || StringUtils.isEmpty(password)) {
                throw new NullPointerException("解密数据库信息为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user.substring(0,user.length()-16));
        dataSource.setPassword(password.substring(0,password.length()-16));
        dataSource.setMinIdle(Integer.parseInt(SIP_MINIDLE));
        dataSource.setMaxActive(Integer.parseInt(SIP_MAXACTIVE));
        //配置获取连接等待超时的时间
        dataSource.setMaxWait(Long.parseLong(SIP_MAXWAIT));
        //配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(SIP_TIMEBETWEENEVICTIONRUNSMILLIS));
        dataSource.setTestOnBorrow(true);
        dataSource.setTestWhileIdle(true);
        //配置一个连接在池中最小生存的时间，单位是毫秒
        dataSource.setMinEvictableIdleTimeMillis(Long.parseLong(SIP_MINEVICTABLEIDLETIMEMILLIS));
        //是否自动回收超时连接
        dataSource.setRemoveAbandoned(true);
        dataSource.setRemoveAbandonedTimeout(Integer.parseInt(SIP_REMOVEABANDONEDTIMEOUT));
        dataSource.setValidationQuery("SELECT 1");
        return dataSource;
    }
 
    @Bean(name = "clusterTransactionManager")
    public DataSourceTransactionManager clusterTransactionManager() {
        return new DataSourceTransactionManager(clusterDataSource());
    }
 
    @Bean(name = "clusterSqlSessionFactory")
    public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource clusterDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(clusterDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(SipDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}